<?php 

/**
 * 
 */
class App_Acl
{
	/**
	 * @var Doctrine\ORM\EntityManager An instance of the entity manager
	 */
	private $_entityManager;
	
	/**
	 * 
	 * @param stdClass $user
	 * @param Zend_Controller_Request_Abstract $request
	 * @param unknown_type $privilege
	 */
	public function isAllowed($user = null, $request = null, $privilege = null) 
	{
		if (isset($user->id) && is_null($user) === false && $user !== false) {
			$userId = $user->id;
		} else {
			$userId = 0;
		}
		
		$this->_entityManager = Zend_Registry::get('em');
		$rsm = new \Doctrine\ORM\Query\ResultSetMapping();
		$rsm->addEntityResult('model\Privilege', 'p');
		$rsm->addFieldResult('p', 'id', 'id');
		$rsm->addFieldResult('p', 'module', 'module');
		$rsm->addFieldResult('p', 'controller', 'controller');
		$rsm->addFieldResult('p', 'action', 'action');
		
		$sql = "SELECT p.id, p.module, p.controller, p.action 
			   	FROM tblPrivilege p 
			   		INNER JOIN tblRole r 
			   			ON r.id = p.role_id 
			   		INNER JOIN tblUserRoles ur 
			   			ON ur.role_id = r.id 
			   	WHERE ur.user_id = ? 
					and 
					(
						p.module = '%' 
						or 
						(
							module = ? 
							and 
							(
								controller = '%' 
								or 
								(
									controller = ? 
									and 
									(
										action = '%' 
										or 
										action = ?
									)
								)
							)
						)
					)
				";
		$query = $this->_entityManager->createNativeQuery($sql, $rsm);
		$query->setParameter(1, $userId);
		$query->setParameter(2, $request->getModuleName());
		$query->setParameter(3, $request->getControllerName());
		$query->setParameter(4, $request->getActionName());
		$privilege = $query->getResult();
		
		if (count($privilege)) {
			return true;
		} else {
			return false;
		}
	}
}